package altserial;

import java.io.IOException;
import java.io.InputStream;

import gnu.io.SerialPort;

public class UploadHandler extends Thread {
	private SerialPort port;
	private boolean inProgress;
	private InputStream in;
	private byte[] buffer;
	private int targetLines;
	
	private final static int BUFFER_SIZE = 1024;
	
	public UploadHandler(SerialPort port, int targetLines) throws IOException {
		this.port = port;
		inProgress = false;
		buffer = new byte[BUFFER_SIZE];
		in = port.getInputStream();
		this.targetLines = targetLines;
	}

	public void run() {
		try {
			inProgress = true;
			int linesRead = 0;
			System.out.println("Thread started");
			while (linesRead < targetLines) {
				int numRead = in.read(buffer);
				linesRead += newlinesIn(numRead);
				System.out.println(new String(buffer, 0, numRead));
				System.out.println("target: " + targetLines + " read: " + linesRead);
			}
			System.out.println("all responses heard");
			in.close();
			System.out.println("input stream closed");
			port.close();
			System.out.println("serial port closed");
			inProgress = false;
		} catch (IOException e) {
			// ???
		}
	}
	
	private int newlinesIn(int numRead) {
		int count = 0;
		for (int i = 0; i < numRead; ++i) {
			if (buffer[i] == '\n') {
				count += 1;
			}
		}
		return count;
	}
	
	public boolean inProgress() {
		return inProgress;
	}
}
